
import 'dart:math';
import 'package:encrypt/encrypt.dart';

class CryptoUtils {
  /// 加密
  /// [plainText] 原始字符串
  /// [key] 密钥
  static String encrypt(String plainText, String key) {
    final keyBytes = Key.fromUtf8(key);
    final ivBytes = IV.fromUtf8(key);
    final encrypter = Encrypter(AES(keyBytes, mode: AESMode.cbc));

    final encrypted = encrypter.encrypt(plainText, iv: ivBytes);
    return encrypted.base64;
  }

  /// 解密
  /// [encryptedText] 加密后的字符串
  /// [key] 密钥
  static String decrypt(String encryptedText, String key) {
    final keyBytes = Key.fromUtf8(key);
    final ivBytes = IV.fromUtf8(key);
    final encrypter = Encrypter(AES(keyBytes, mode: AESMode.cbc));

    final decrypted = encrypter.decrypt64(encryptedText, iv: ivBytes);
    return decrypted;
  }

  /// 随机生成16位密钥大小写字母和数字组合
  static String randomKey() {
    String alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    int strLength = 16;
    String left = '';
    for (int i = 0; i < strLength; i++) {
      left = left + alphabet[Random().nextInt(alphabet.length)];
    }
    return left;
  }

/**
 * 这里有个坑需要避免一下，加密出来的内容是带了 + / = 这几个非url安全字符的，需要替换
    + 替换为 *
    / 替换为 - 中划线
    = 替换为 _A 下划线加字母A
 */
  static String urlSafeBase64Encode(String str) {
    return str.replaceAll('+', '*').replaceAll('/', '-').replaceAll('=', '_A');
  }

  static String urlSafeBase64Decode(String str) {
    return str.replaceAll('*', '+').replaceAll('-', '/').replaceAll('_A', '=');
  }
}

void main() {
  // 示例原始字符串
  String originalString = '{"pc": "邀请码","apiUrl": "http://www.abc.com","id": "视频id"}';
  // 生成随机密钥
  String randomKey = CryptoUtils.randomKey();
  print('随机密钥: $randomKey');
  // 加密
  String encryptedString = CryptoUtils.urlSafeBase64Encode(CryptoUtils.encrypt(originalString, randomKey));
  print('加密后的字符串: ${encryptedString}');

  // 解密
  String decryptedString = CryptoUtils.decrypt(CryptoUtils.urlSafeBase64Decode(encryptedString), randomKey);
  print('解密后的字符串: ${decryptedString}');
}